package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 入住Service业务层处理
 *
 * @author zzyl
 * @date 2025-10-16
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    @Autowired
    private  ContractMapper contractMapper;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 入住申请
     *
     * @param dto
     */
    @Override
    @Transactional
    public void CheckInApply(CheckInApplyDto dto) {
        //1.先根据老人填的身份证,来查询养老院的数据库中是否已经有该老人,
        //且老人的入住状态是否为已入住,如果已经有了且入住状态为已入住,
        //则直接返回提示信息,该老人已入住
        String idCardNo = dto.getCheckInElderDto().getIdCardNo();
        Elder OldElder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery().eq(Elder::getIdCardNo, idCardNo).eq(Elder::getStatus, 1));
        if (ObjectUtil.isNotEmpty(OldElder)) {
            throw new BaseException("该老人已入住");
        }
        //2.如果老人不满足上面的条件,查询老人想要入住的床位信息,
        //将床位的状态,改为已入住
        Bed bed = bedMapper.selectBedById(dto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        //3.根据老人的身份证信息来判断老人是否在养老院的数据库中已存在,
        //如果已存在就更改,如果不存在就新增,记得把信息补全
        //属性拷贝
        Elder elder = updateOrInsertElderMessage(dto, bed);
        //4.新增入住信息及入住配置表,还有家属信息,记得补全信息
        insertCheckInAndCheckInConfig(dto, elder);
        //5.新增合同信息
        insertContract(dto, elder);
    }

    /**
     * 查询入住详情
     * @param id 入住id
     * @return 封装的数据
     */
    @Override
    @Transactional
    public CheckInDetailVo detail(Long id) {
        //根据入住id查询入住信息及入住配置表并封装
        CheckIn checkIn = checkInMapper.selectCheckInById(id);
        BeanUtil.toBean(checkIn, CheckInConfigVo.class);
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(Wrappers.<CheckInConfig>lambdaQuery().eq(CheckInConfig::getCheckInId, checkIn.getId()));
        CheckInConfigVo checkInConfigVo = BeanUtil.toBean(checkInConfig, CheckInConfigVo.class);
        //根据checkIn中的老人id查询老人的信息封装checkinElderVo
        Elder elder = elderMapper.selectElderById(checkIn.getElderId());
        //计算老人年龄
        String birthday = elder.getBirthday();
        int age = DateUtil.ageOfNow(birthday);
        CheckInElderVo checkInElderVo = BeanUtil.toBean(elder, CheckInElderVo.class);
        checkInElderVo.setAge(age);
        //根据elder中的备注来封装家属信息ElderFamilyVo
    // 2. 解析家属信息（修改 detail 方法）
    // 原代码：List<ElderFamilyVo> elderFamilyVoList=(JSON.parseArray(elder.getRemark(), ElderFamilyVo.class));
    // 新代码：处理空值，解析失败时返回空数组
        List<ElderFamilyVo> elderFamilyVoList=(JSON.parseArray(elder.getRemark(), ElderFamilyVo.class));
//        String familyRemark = elder.getRemark();
//        List<ElderFamilyVo> elderFamilyVoList = new ArrayList<>(); // 默认空数组
//        if (ObjectUtil.isNotEmpty(familyRemark)) {
//            try {
//                // 用 Hutool 解析，避免工具类混用
//                elderFamilyVoList = JSONUtil.toList(familyRemark, ElderFamilyVo.class);
//            } catch (Exception e) {
//                log.error("解析家属信息失败", e);
//                // 解析失败仍返回空数组，避免前端报错
//                elderFamilyVoList = new ArrayList<>();
//            }
//        }
        //根据老人id查询合同信息,封装contract
        Contract contract = contractMapper.selectOne(Wrappers.<Contract>lambdaQuery().eq(Contract::getElderId, elder.getId()));

        //封装返回的数据
        //把入住配置的入住时间加上
        checkInConfigVo.setStartDate(contract.getStartDate());
        checkInConfigVo.setEndDate(contract.getEndDate());
        CheckInDetailVo checkInDetailVo =new CheckInDetailVo();
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVoList);
        checkInDetailVo.setContract(contract);
        return checkInDetailVo;
    }

    private  void insertContract(CheckInApplyDto dto, Elder elder) {
        Contract contract = BeanUtil.toBean(dto.getCheckInContractDto(), Contract.class);
        contract.setElderId(Math.toIntExact(elder.getId()));
        contract.setElderName(elder.getName());
        contract.setContractName(contract.getContractName());
        contract.setStartDate(dto.getCheckInConfigDto().getStartDate());
        contract.setEndDate(dto.getCheckInConfigDto().getEndDate());
        contract.setStatus(contract.getStartDate().isBefore(LocalDateTime.now()) ? 1 : 0);
        contract.setContractNumber(CodeGenerator.generateContractNumber());
        contractMapper.insert(contract);
    }

    private void insertCheckInAndCheckInConfig(CheckInApplyDto dto, Elder elder) {
        //新增入住信息
        CheckIn checkIn = BeanUtil.toBean(dto.getCheckInConfigDto(), CheckIn.class);
        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setStatus(0);
        checkInMapper.insert(checkIn);
        //新增入住配置表,和家人信息,家人信息是保存到备注里
        CheckInConfig checkInConfig = BeanUtil.toBean(dto.getCheckInConfigDto(), CheckInConfig.class);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfig.setRemark(dto.getElderFamilyDtoList().toString());
        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     * 根据老人的身份证信息来判断老人是否在养老院的数据库中已存在,
     * 如果已存在就更改,如果不存在就新增,记得把信息补全
     *
     * @param dto 前端传过来的数据
     * @param bed 老人选中的床位信息
     * @return 老人的基本信息
     */
    private Elder updateOrInsertElderMessage(CheckInApplyDto dto, Bed bed) {
        Elder newEler = BeanUtil.toBean(dto.getCheckInElderDto(), Elder.class);
        newEler.setStatus(1);
        newEler.setBedId(dto.getCheckInConfigDto().getBedId());
        newEler.setBedNumber(bed.getBedNumber());
        newEler.setRemark(JSON.toJSONString(dto.getElderFamilyDtoList()));
        Elder elderMeg = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery().eq(Elder::getIdCardNo, newEler.getIdCardNo()).ne(Elder::getStatus, 1));
        if (ObjectUtil.isNotEmpty(elderMeg)) {
            //存在该老人,更新该老人的状态并补全信息
            elderMapper.updateElder(newEler);
        } else {
            elderMapper.insert(newEler);
        }
        return newEler;
    }
}
